#include <WiFi.h>
#include <WebSocketClient.h>
#include <string.h>
#include <ArduinoJson.h>
#include <HardwareSerial.h>
#define BAUD_RATE 115200

//指示灯定义
const int greenPin = 14;
const int redPin = 26;
//WiFi信息
//WIFI名称：1212
const char* ssid     = "1527";
//WIFI密码：guolaoshi666
const char* password = "15271527";

//websocket服务器地址:118.24.9.48:8282
char path[] = "/";
//服务器IP
char host[] = "118.24.9.48";
//websocket端口
unsigned int websocket_port =8282;
//设备唯一编号
String pid ="19980713";

//课程号
const char*  course_id;
//开关信号
String StartRX = "0";
//读缓存拼接数组
String redbufer;
//读字节
byte reder;
//读取指令
byte a_READCMD[7] = {187, 0, 34, 0, 0, 34, 126};
//byte a_READCMD[10] = {0xBB,0x00,0x27,0x00,0x03,0x22,0xFF,0xFF,0x4A,0x7E};


//软串口类定义，RX 16  TX 17
HardwareSerial swSer(1);

//json字符串转数组
StaticJsonDocument<256> doc;


//使用websocketClient类创建websocket连接
WebSocketClient webSocketClient;
//使用WiFiClient类创建TCP连接
WiFiClient client;

void setup() {
  // put your setup code here, to run once:
  //初始化串口
  pinMode(greenPin, OUTPUT);
  pinMode(redPin, OUTPUT);
  digitalWrite(greenPin, LOW);
    digitalWrite(redPin, LOW);
  Serial.begin(115200);
  swSer.begin(BAUD_RATE, SERIAL_8N1, 16, 17);
  delay(10);
  Serial.println("Serials has opened!");
  //初始化WiFi
  Serial.print("Connecting WiFi = ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.print("IP address = ");
  Serial.println(WiFi.localIP());
  delay(3000);

  //连接websocket服务器
  if (client.connect(host, websocket_port)) {
    Serial.println("Connected");
  } else {
    Serial.println("Connection failed.");
  }

  webSocketClient.path = path;
  webSocketClient.host = host;
  //websocket握手
  if (webSocketClient.handshake(client)) {
    Serial.println("Handshake successful");

    String initType = "{\"type\": \"init\",\"pid\":"+String(pid)+"}";

    webSocketClient.sendData(initType);
    Serial.println(initType);

  } else {
    //加红灯
    digitalWrite(redPin, HIGH);
    Serial.println("Handshake failed.");
    while(1);
  }



}

void loop() {
  // put your main code here, to run repeatedly:
  String data;
  if (client.connected()) {

    webSocketClient.getData(data);
    if (data.length() > 0) {
      Serial.print("Received data: ");
      Serial.println(data);
      //        deserializeJson(doc,data);
    
      deserializeJson(doc, data);
      const char*  type = doc["type"];
      //        switch(type){
      if (doc["type"] == "startup")
      {
        StartRX = "1";
        course_id = doc["course_id"];
      } else if (doc["type"] == "close")
      {
        StartRX = "0";
        course_id = "";
      }
    }

    GetMessgFormRXswSer();

  }


}


void GetMessgFormRXswSer() {


  if (StartRX == "1"){
    //加绿灯
    digitalWrite(greenPin, HIGH);
    swSer.write(&a_READCMD[0], 7);
    delay(300);
    if (swSer.available() > 0) {
      Serial.println("---scaning----");
      while (swSer.available()) {
        //      Serial.println(swSer.read(),HEX);
        if (swSer.read() == 0xBB) {
          delay(5);
          if (swSer.read() == 0X02) {
            delay(5);
            if (swSer.read() == 0X22) {
              delay(5);
              if (swSer.read() == 0X00) {
                delay(5);
                if (swSer.read() == 0X11) {
                  delay(5);
                  for (int i = 0; i < 15; i++) {
                    reder = swSer.read();
                    delay(5);
                    if (i > 2) {
                      redbufer += char(reder);
                    }
                  }
                  Serial.println("-----------");
                  //            Serial.println(redbufer);
                  String initType1 = "{\"type\": \"work\",\"course_id\":" + String(course_id) + ",\"student\":" + String(redbufer) + "}";
                  Serial.println(initType1);
                  webSocketClient.sendData(initType1);
                  redbufer = "";
                  Serial.println("-----------");
                }
              }
            }
          }
        }
      }
    }

  }else{
    digitalWrite(greenPin, LOW);
  }
}
